﻿using Microsoft.AspNetCore.SignalR;
using System.Security.Claims;

namespace OA.Infrastructure.SignalR.Hubs;

public class NotifyHub : Hub
{
    private readonly IDictionary<string, string> _connections = new Dictionary<string, string>();

    public async Task AddToGroup(string groupName)
    {
        var username = Context.User?.FindFirst(ClaimTypes.Name)?.Value!;
        var connectionId = Context.ConnectionId;

        _connections.TryAdd(connectionId, username);

        await Groups.AddToGroupAsync(connectionId, groupName);
    }

    public async Task RemoveFromGroup(string groupName)
    {
        var connectionId = Context.ConnectionId;

        _connections.Remove(connectionId);

        await Groups.RemoveFromGroupAsync(connectionId, groupName);
    }

    public async Task SendMessage(string message)
    {
        await Clients.All.SendAsync("ReceiveNotification", message);
    }

    public async Task SendMessageToGroup(string message, string groupName)
    {
        await Clients.Group(groupName).SendAsync("ReceiveNotification", message);
    }

    public async Task SendMessageToUser(string message, string userId)
    {
        await Clients.User(userId).SendAsync("ReceiveNotification", message);
    }

    public override Task OnConnectedAsync()
    {
        return base.OnConnectedAsync();
    }

    public override Task OnDisconnectedAsync(Exception? exception)
    {
        return base.OnDisconnectedAsync(exception);
    }
}